<script setup>
import { ref, watchEffect, computed } from 'vue'
import { CScrollbar } from 'c-scrollbar'

// 定义父组件传来的参数
const props = defineProps({
  kind: { // 多个下拉列表的不同标识
    type: Number,
    required: false,
    default: 1
  },
  selList: { // 下拉列表数据
    type: Array,
    required: false,
    default: []
  },
  inboxed: { // 是否跟随界面滚动
    type: Boolean,
    required: true,
    default: false
  },
  curName: { // 当前显示的Label名称
    type: String,
    default: ''
  },
  preName: { // 下拉框默认的名称前缀
    type: String,
    default: ''
  }
})

const curName = ref('')
watchEffect(() => {
  curName.value = props.curName
})

// emits 定义调用父级方法
const emits = defineEmits(['setValue'])

const selShow = ref(false)
// showSelect 显示下拉框
const showSelect = () => {
  selShow.value = true
}
// hideSelect 隐藏下拉框
const hideSelect = () => {
  selShow.value = false
}

// setValue 赋值
const setValue = (cur) => {
  emits('setValue', cur, props.kind)
}

// schList 通过关键字筛选
const schList = computed(() => props.selList.filter((item) => item.selName.includes(curName.value) || item.selCode.includes(curName.value)))

// clrTxt 清除文本
const clrTxt = () => {
  curName.value = ''
}
</script>

<template>
  <div :class="[inboxed ? 'sel-a' : '']">
    <input type="text" v-model="curName" :placeholder="'请选择'+preName" class="ipt" @focus="showSelect" @blur="hideSelect" />
    <i v-show="curName!==''" class="iconfont sel-b" @click="clrTxt">&#xea7f;</i>
    <transition name="fade-mod" appear>
      <div class="sel-c" v-show="selShow">
        <div class="sel-d">
          <c-scrollbar>
            <div class="sel-e dan" v-for="curSel in schList" :key="curSel.selId" @click="setValue(curSel)">{{curSel.selName}}{{curSel.selCode ? '['+curSel.selCode+']' : ''}}</div>
          </c-scrollbar>
        </div>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.sel-a {width: 240px; position: relative;}
.sel-b {position: absolute; margin: 11px 0 0 -26px; color: #999; cursor: pointer;}
.sel-c {position: absolute; z-index: 4;}
.sel-d {min-width: 230px; height: 200px; overflow: hidden; background-color: #FFF; box-shadow: 0 2px 3px #999;}
.sel-e {height: 40px; line-height: 40px; padding: 0 20px; border-bottom: 1px solid #EEE; cursor: pointer;}
.sel-e:hover {background-color: #E9EEF2;}
</style>
